package com.gitee.core.dubbo.core;

import com.gitee.core.dubbo.DubboServiceException;
import com.gitee.core.dubbo.RpcManager;
import com.google.common.base.Strings;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class ServiceCall implements Serializable {
    private static final long serialVersionUID = 2873828239238L;

    private ServiceCallAdapter adapter;

    public ServiceCall(ServiceCallAdapter adapter) {
        this.adapter = adapter;
    }

    public CallResult invoke() {
        String systemName = adapter.getSystem();
        if (Strings.isNullOrEmpty(systemName)) {
            throw new DubboServiceException("远程系统未定义");
        }

        String serviceName = adapter.getService();
        if (Strings.isNullOrEmpty(serviceName)) {
            throw new DubboServiceException("远程服务未定义");
        }

        String methodName = adapter.getMethod();
        if (Strings.isNullOrEmpty(methodName)) {
            throw new DubboServiceException("远程方法未定义");
        }

        RpcManager rpc = (RpcManager) SpringApplicationContext.getBean(systemName);

        if (rpc == null) {
            throw new DubboServiceException("远程系统未定义");
        }
        Map data = adapter.getData();
        data = data == null ? new HashMap<String, Object>() : data;
        Service service = new Service(systemName, serviceName, methodName, data);
        return rpc.invoke(service);
    }

}